#include "dataset.h"
#include "dpalgo.h"
#include <fstream>

using namespace std;

static bool set_srand = false;

static int dataSetInfo[][2] = {
	{8, 3},
	{10, 1},
	{21, 1},
	{10, 1},
	{9, 1},
	{6, 1},
	{10, 1},
};

static char dataSetName[][3][MAX_DATASETNAME_LEN] = {
	{"./dataset/p01_c.txt","./dataset/p01_w.txt", "./dataset/p01_s.txt",},
	{"./dataset/p02_c.txt","./dataset/p02_w.txt", "./dataset/p02_s.txt",},
	{"./dataset/p03_c.txt","./dataset/p03_w.txt", "./dataset/p03_s.txt",},
	{"./dataset/p04_c.txt","./dataset/p04_w.txt", "./dataset/p04_s.txt",},
	{"./dataset/p05_c.txt","./dataset/p05_w.txt", "./dataset/p05_s.txt",},
	{"./dataset/p06_c.txt","./dataset/p06_w.txt", "./dataset/p06_s.txt",},
	{"./dataset/p07_c.txt","./dataset/p07_w.txt", "./dataset/p07_s.txt",},
};

void GetDataSet(DataSet &ds, int id) {
	ds.nums.clear();

	if (id < 0 || id >= DATASET_FILE_NUM) {
		printf("Wrong dataset id!\n");
		return;
	}

	int n, u, cnt, tmp;
	ds.flag = true;
	ds.id = id;
	ds.n = n = dataSetInfo[id][0];

	ifstream ds_c(dataSetName[id][0]);
	ifstream ds_w(dataSetName[id][1]);

	ds_c >> u;
	ds.u = u;

	for (cnt = 0; cnt < n; ++cnt) {
		ds_w >> tmp;
		ds.nums.push_back(tmp);
	}

	ds_c.close();
	ds_w.close();
}

/* Get number between [startm, end] */
static int RandomNum(int start, int end) {
	if (end < start) {
		return start - 1;
	}

	int dist = end - start + 1;

	return rand() % dist + start;
}

void GetRandomDataSet(DataSet &ds) {
	ds.nums.clear();

	int n, u, cnt;

	if (set_srand)
		srand(rand());
	else{
		srand(time(0));
		set_srand = true;
	}
	
	n = RandomNum(MIN_SET_SIZE, MAX_SET_SIZE);
	u = RandomNum(n * MIN_NUMBER_SIZE, n * MAX_NUMBER_SIZE);

	ds.flag = false;
	ds.id = -1;
	ds.n = n;
	ds.u = u;

	for (cnt = 0; cnt < n; ++cnt) {
		(ds.nums).push_back(RandomNum(MIN_NUMBER_SIZE, MAX_NUMBER_SIZE));
	}
	return;
}

int GetStdSolution(DataSet &ds) {
	if (ds.flag) {
		char junk;
		int id, n, cnt, res, tmp;
		res = 0;
		n = ds.n;
		id = ds.id;

		if (id < 0 || id >= DATASET_FILE_NUM) {
			printf("Wrong dataset id!\n");
			return -1;
		}

		ifstream ds_s(dataSetName[id][2]);
		if (dataSetInfo[id][1] > 1) {
			for (cnt = 0; cnt < n; ++cnt) {
				ds_s >> tmp;
				res += ds.nums[cnt] * tmp;
				do {
					ds_s.get(junk);
				} while (!ds_s.eof() && junk != '\n');
			}
		} else {
			for (cnt = 0; cnt < n; ++cnt) {
				ds_s >> tmp;
				res += ds.nums[cnt] * tmp;
			}
		}

		return res;
	} else {
		return DPSubSetSum(ds);
	}
}

void DispDataSet(DataSet &ds) {
	if (ds.flag)
		printf("DataSet(id = %d):\t", ds.id);
	else
		printf("Random DataSet:\t");

	printf("n = %d\tu = %d\n", ds.n, ds.u);
	for (int cnt = 0; cnt < (ds.n); ++cnt) {
		printf("%d\t", (ds.nums)[cnt]);
		if ((cnt + 1) % 5 == 0)
			putchar('\n');
	}

	if (ds.n % 5) {
		putchar('\n');
	}
	return;
}
